package com.wz.getsignaturetool;

import java.security.MessageDigest;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

/**
 * 获取应用签名信息
 * @author LWEI
 */
public class MainActivity extends Activity {

	private EditText mPkg_edt;
	private TextView mKey_tv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mPkg_edt = (EditText) findViewById(R.id.packagename_edt);
		mKey_tv = (TextView) findViewById(R.id.key_tv);
		findViewById(R.id.getKey_btn).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String packageName = mPkg_edt.getText().toString();
				String signature = getSignatureStr(getApplication(), packageName);
				mKey_tv.setText(signature);
				Log.i("keytool", "签名:" + signature);
			}
		});
	}

	private static String getSignatureStr(Context context, String packageName) {
		String result = null;
		try {
			PackageManager packageManager = context.getPackageManager();
			PackageInfo packageInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
			if (null != packageInfo) {
				Signature[] signatures = packageInfo.signatures;
				result = encodeMd5(signatures[0].toByteArray());
			}
		} catch (Exception e) {
			result = e.getMessage();
		}
		return result;
	}

	/**
	 * 字符串转md5
	 * @author wei 
	 * @param plainText
	 * @return
	 */
	public static String encodeMd5(byte[] plainText) {
		String result = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText);
			byte b[] = md.digest();
			int i;
			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			result = buf.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

}
